using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using AppExtensions.Exceptions;

namespace AppExtensions.Helpers
{
    public static class Guard
    {
        public static void ConnectionStringIsConnectable(string connectionStringName)
        {
            ConnectionStringSettings connectionStringSetting = ConfigurationManager.ConnectionStrings[connectionStringName];
            if (connectionStringSetting == null)
                throw new ConnectionStringMissingException(connectionStringName);
            if(connectionStringSetting.ProviderName == null)
                throw new ConnectionStringProviderNameMissingException(connectionStringName);

            System.Data.Common.DbProviderFactory dbpf = System.Data.Common.DbProviderFactories.GetFactory(connectionStringSetting.ProviderName);
            if(dbpf == null)
                throw new ConnectionStringProviderNameUnknownException(connectionStringName);

            System.Data.Common.DbConnection connection = dbpf.CreateConnection();
            try
            {
                connection.Open();
            }
            catch
            {
                throw new ConnectionStringNotConnectableException(connectionStringName);
            }
            finally
            {
                if (connection.State != System.Data.ConnectionState.Closed)
                    connection.Close();
            }
        }

        public static void ParameterIsGuid(System.Collections.Specialized.NameValueCollection nameValueCollection, string p)
        {
            if (nameValueCollection[p] == null)
                throw new ParameterNotFoundException(p);
            
            string value = nameValueCollection[p];
            try
            {
                Guid guid = new Guid(value);
            }
            catch (Exception)
            {
                throw new WrongTypeParameterException<Guid>(p);
            }
        }
    }
}
